import datetime
from django.db import models
from rest_framework.viewsets import ModelViewSet

from user.models import User
from .models import Anchor, Bug
from device.models import Device
from .serializers import AnchorSrializer, BugeSrializer
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import fields, filters
from logger.models import Logger
from common.constant import CODE_SUCCESS, CODE_PARAMETER_ERROR, CODE_BUSSINESS_ERROR, MSG_PARAMETER_ERROR
from common.response import JsonResponse
from user.authentication_module import TokenAuth
import json
from django_filters.rest_framework import FilterSet
from rest_framework.decorators import action


class BugFilter(FilterSet):
    class Meta:
        models = Bug
        fields = {
            'state': ['exact'],
            'createUser': ['exact'],
            'handleUser': ['endswith'],
        }

    @property
    def qs(self):
        parent = super().qs
        relevantUser = self.request.query_params.get('relevantUser', None)
        state = self.request.query_params.get('state', None)

        if relevantUser:
            return (parent.filter(handleUser__endswith=relevantUser) |
                    parent.filter(createUser=relevantUser))\
                .filter(state=state)
        else:
            return parent


class BugViewSet(ModelViewSet):
    queryset = Bug.objects.all().order_by('-createTime')
    serializer_class = BugeSrializer
    filter_backends = (DjangoFilterBackend,
                       filters.SearchFilter, filters.OrderingFilter)
    filterset_class = BugFilter
    authentication_classes = [TokenAuth]

    @action(detail=True, methods='POST')
    def assign(self, request, *args, **kwargs):
        try:
            bugId = request.data['bugId']
            targetId = request.data['targetId']
        except Exception:
            return JsonResponse(data=None, code=CODE_PARAMETER_ERROR, message=MSG_PARAMETER_ERROR)
        try:
            bug = self.queryset.get(bugId=bugId)
            bug.handleUser = "%s,%s" % (bug.handleUser, targetId)
            bug.save()
        except Exception as e:
            return JsonResponse(data=None, code=CODE_BUSSINESS_ERROR, message=e.__str__)
        return JsonResponse(data=None)

    def update(self, request, pk, *args, **kwargs):
        try:
            bug = self.queryset.get(bugId=pk)
            state = request.data["state"]
            bug.state = state
            bug.save()
        except Exception as e:
            return JsonResponse(data=None, code=CODE_BUSSINESS_ERROR, message=e.__str__)
        return JsonResponse(data=None)


class AnchorViewSet(ModelViewSet):
    queryset = Anchor.objects.all().order_by('-createTime')
    serializer_class = AnchorSrializer
    authentication_classes = [TokenAuth]
    filter_fields = ('createUser',)

    def create(self, request, *args, **kwargs):
        try:
            createUserId = request.data['createUserId']
            deviceId = request.data['deviceId']
            startTime = int(request.data['startTime'])
            endTime = int(request.data['endTime'])
        except Exception:
            return JsonResponse(data=None, code=CODE_PARAMETER_ERROR, message=MSG_PARAMETER_ERROR)

        try:
            startTime = datetime.datetime.fromtimestamp(startTime)
            endTime = datetime.datetime.fromtimestamp(endTime)
        except Exception:
            startTime = datetime.datetime.fromtimestamp(startTime/1000)
            endTime = datetime.datetime.fromtimestamp(endTime/1000)

        if(startTime < endTime):
            result = Logger.objects.filter(
                deviceId=deviceId, createTime__range=(startTime, endTime))
        else:
            result = Logger.objects.filter(
                deviceId=deviceId, createTime__range=(endTime, startTime))

        resultData = []
        for item in result:
            resultData.append(item.content)

        if len(resultData):
            Anchor.objects.create(createUser=User.objects.get(id=createUserId),
                                  device=Device.objects.get(id=deviceId), loggerContnet=resultData)
            return JsonResponse(data=None, code=CODE_SUCCESS, message='anchor创建成功')
        else:
            return JsonResponse(data=None, code=CODE_PARAMETER_ERROR, message='该时间段没有日志')

    def destroy(self, request, *args, **kwargs):
        try:
            super().destroy(request, *args, **kwargs)
        except Exception:
            return JsonResponse(data=None, code=CODE_BUSSINESS_ERROR, message="删除失败")
        return JsonResponse(data=None)
